<template>
  <div class="manageShops-container">
    <div class="header-container">
      <el-form :model="form" label-width="80px" ref="seachRef">
        <el-row :gutter="20">
          <el-col :span="8">
            <xm-f-intput
              v-model="form.title"
              prop="medicineName"
              label="商品名称:"
            ></xm-f-intput>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类:" prop="saleTypeId">
              <add-types-dialog
                v-model="form.types"
                :type="2"
              ></add-types-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <xm-f-intput
              v-model="form.goodsCode"
              label="商品编码:"
              prop="id"
            ></xm-f-intput>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <xm-f-intput
              v-model="form.id"
              label="商品ID:"
              prop="id"
            ></xm-f-intput>
          </el-col>
          <el-col :span="9">
            <el-form-item label="创建时间:" prop="time">
              <XMDatePicker
                v-model="form.time"
                v-model:startTime="form.startTime"
                v-model:endTime="form.endTime"
                type="daterange"
                disabledDateT="after"
                label="选择开始时间:"
                style="width: 180px"
                :config="{ shortcuts: true }"
              ></XMDatePicker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="价格区间:" prop="time">
              <el-input
                v-number:2
                v-model="form.minPrice"
                style="width: 45%"
              ></el-input>
              至
              <el-input
                v-number:2
                v-model="form.maxPrice"
                style="width: 45%"
                @change="maxPriceChange"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="库存区间:"
              label-width="100px"
              prop="termValidity"
            >
              <el-input
                v-number
                v-model="form.minStock"
                style="width: 45%"
              ></el-input>
              至
              <el-input
                v-number
                v-model="form.maxStock"
                style="width: 45%"
                @change="maxStockChange"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="3">
            <el-button @click="loadData" type="primary" style="width: 100%">
              筛选
            </el-button>
          </el-col>
          <el-col :span="3">
            <el-button @click="clear" style="width: 100%">清空</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="content-container">
      <div class="shop-table-header">
        <el-radio-group
          v-model="form.status"
          style="margin-bottom: 30px"
          @change="loadData"
        >
          <el-radio-button :label="-1">全部</el-radio-button>
          <el-radio-button :label="1">出售中</el-radio-button>
          <el-radio-button :label="2">已售完</el-radio-button>
          <el-radio-button :label="0">已下架</el-radio-button>
        </el-radio-group>
        <el-button type="primary" @click="edit({}, 1)">新增商品</el-button>
      </div>
      <div class="selClass">
        <!-- <el-checkbox
          v-model="d.search.allChecked"
          @change="allCheckedChange"
        ></el-checkbox> -->
        <span>已选{{ sellength }}项，批量设置</span>
        <el-button type="primary" @click="showFuncHub(1)">追加分类</el-button>
        <el-button type="primary" @click="showFuncHub(2)">改价格</el-button>
        <el-button type="primary" @click="showFuncHub(3)">上架</el-button>
        <el-button type="primary" @click="showFuncHub(4)">下架</el-button>
        <el-button type="danger" @click="showFuncHub(5)">删除</el-button>
      </div>

      <PaginationTable
        ref="ptable"
        :tableData="d.listData"
        @pagination="paginaChange"
        :getPTbale="paginationTableRef"
        @cellSelectChange="cellSelectChange"
      >
        <el-table-column type="selection" width="55" />
        <XMTableColumn label="商品名称" prop="id" width="450">
          <template #default="scope">
            <div class="cell-img">
              <ImageView v-model="scope.row.images"></ImageView>
              <div>
                <el-popover
                  placement="top-start"
                  :width="200"
                  trigger="hover"
                  title="商品名"
                  :content="scope.row.title"
                >
                  <template #reference>
                    <span>{{ scope.row.title }}</span>
                  </template>
                </el-popover>
                <span>{{ scope.row.specValue }}</span>
              </div>
            </div>
          </template>
        </XMTableColumn>
        <XMTableColumn label="排序" prop="medicineName" width="200px">
          <template #default="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              :icon="Top"
              @click="shopUpOnceSort(1, row, $index)"
            />
            <el-button
              type="primary"
              size="small"
              :icon="Bottom"
              @click="shopUpOnceSort(2, row, $index)"
            />
            <el-button
              type="warning"
              size="small"
              :icon="Download"
              style="transform: rotate(180deg)"
              @click="shopUpTopSort(row, $index)"
            />
          </template>
        </XMTableColumn>
        <XMTableColumn label="价格" prop="price" sortable="custom">
          <template #default="scope">{{ scope.row.price / 100 }}元</template>
        </XMTableColumn>
        <XMTableColumn
          label="销量"
          prop="totalSales"
          sortable="custom"
        ></XMTableColumn>
        <XMTableColumn
          label="库存"
          prop="stock"
          sortable="custom"
        ></XMTableColumn>
        <XMTableColumn label="创建时间" prop="createTime"></XMTableColumn>
        <XMTableColumn label="状态" prop="status">
          <template #default="scope">
            {{
              shopsStatusDic().find((item) => scope.row.status === item.value)
                ?.label
            }}
          </template>
        </XMTableColumn>
        <XMTableColumn label="商品编码" prop="goodsCode"></XMTableColumn>
        <XMTableColumn label="商品ID" prop="id"></XMTableColumn>
        <XMTableColumn label="操作" width="280">
          <template #default="scope">
            <el-button
              size="small"
              text
              type="primary"
              @click="edit(scope.row, 1)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              text
              type="primary"
              @click="edit(scope.row, 2)"
            >
              分享
            </el-button>

            <el-button
              size="small"
              text
              type="primary"
              @click="edit(scope.row, 3)"
            >
              {{ scope.row.status === 0 ? '上架' : '下架' }}
            </el-button>

            <el-button
              size="small"
              text
              type="danger"
              @click="edit(scope.row, 4)"
            >
              删除
            </el-button>
          </template>
        </XMTableColumn>
      </PaginationTable>
    </div>
    <add-types-dialog
      ref="addTypesRef"
      :selItems="selArrays"
      v-model:dia-log-visible="addTypesDialogShow"
      @addSuccess="loadData"
    />
    <batch-price-change-comp
      v-model:dia-log-visible="batchPriceShow"
      :selItems="selArrays"
      @addSuccess="loadData"
    ></batch-price-change-comp>
  </div>
</template>
<script lang="ts" setup>
  import { useRouter } from 'vue-router'
  import { reactive, ref, computed, watch } from 'vue'
  import { Top, Bottom, Download } from '@element-plus/icons-vue'
  import {
    getShopList,
    unsaleable,
    saleable,
    deleteShops,
    upTopSort,
    upOnceSort,
  } from '@/api/modules/shop'
  import type { unsaleableType } from '@/api/modules/shop'
  import { onMountedOrActivated } from '@/hooks/core/onMountedOrActivated'
  import ImageView from '@/components/ImageView/index.vue'
  import { usePromise } from '@/hooks/core/usePromise.js'
  import common from '@/utils/common'
  import { useStore } from 'vuex'
  import type { shop } from '@/types/shop'
  import addTypesDialog from '../../components/addTypesDialog/index.vue'
  // eslint-disable-next-line max-len
  import batchPriceChangeComp from '../../components/batchPriceChangeComp/index.vue'
  import { useTableSort, useStops } from '../../hooks/useShops'
  import { cloneDeep } from 'lodash'
  interface headerForm {
    // 商品名称
    title?: string
    // 分类
    types?: number[]
    // 商品编码
    goodsCode?: number
    // 商品分类id
    goodsTypeId?: number
    // 营销id
    saleTypeId?: number
    // 时间
    time?: string
    // 开始时间
    startTime?: number
    // 结束时间
    endTime?: number
    // 最小价格
    minPrice?: number
    // 最大价格
    maxPrice?: number
    // 最大库存
    maxStock?: number
    // 最小库存
    minStock?: number
    // 状态（-1：全部，0：下架，1：销售，2：售完）
    status?: number
    id?: number
    sortPrice?: number
    sortSales?: number
    sortStock?: number
  }

  const { to } = usePromise()
  const { shopsStatusDic } = useStops()
  const router = useRouter()
  const store = useStore()
  const form = reactive<headerForm>({ status: -1 })

  interface ListData {
    listData: {
      data: any[]
    }
    search: any
  }
  const d = reactive<ListData>({
    search: { allChecked: false, pageIndex: 1, pageSize: 5 },
    listData: { data: [] },
  })

  onMountedOrActivated(() => {
    loadData()

    if (!store.getters.expressTypes || store.getters.expressTypes.length <= 0) {
      store.dispatch('shop/setExpressTypes')
    }
  })

  async function loadData() {
    function initForm(form: headerForm) {
      const tmp = cloneDeep(form)
      if (tmp.status === -1) delete tmp.status
      if (tmp.minPrice) tmp.minPrice = tmp.minPrice * 100
      if (tmp.maxPrice) tmp.maxPrice = tmp.maxPrice * 100

      // if (tmp.minStock) tmp.minStock = tmp.minStock
      // if (tmp.maxStock) tmp.maxStock = tmp.maxStock

      if (tmp.types) {
        //  { name: '商品分类', id: 1, isParent: true },
        //   { name: '营销分类', id: 2, isParent: true },
        const [n1, n2] = tmp.types
        n1 === 1 ? (tmp.goodsTypeId = n2) : (tmp.saleTypeId = n2)
      }
      return tmp
    }
    const data = { ...d.search, ...initForm(form) }
    const [err, res] = await to(getShopList(data))
    if (!err) {
      d.listData = res
      d.listData.data = d.listData.data.map((element: any) => {
        if (element.goodsCode) {
          element.specValue = '单规格'
        } else {
          element.specValue = '多种规格'
        }
        return element
      })
    }
  }
  // 还原条件
  const ptable = ref()
  async function clear() {
    d.search = { allChecked: false, pageIndex: 1, pageSize: 5 }
    Object.keys(form).forEach((key) => {
      if (key !== 'status') {
        delete form[key as keyof headerForm]
      } else {
        form.status = -1
      }
    })
    ptable.value.clearData()
    loadData()
  }
  // function paginaChange(params: any) {
  //   d.search.pageIndex = params.current
  //   d.search.pageSize = params.pageSize
  //   loadData()
  // }

  // 选中或取消的
  const selArrays = ref<Partial<shop[]>>()
  function cellSelectChange(selection: shop[]) {
    selArrays.value = selection
  }
  const sellength = computed(() => {
    return selArrays.value?.length || 0
  })
  function allCheckedChange() {}
  // header
  const addTypesDialogShow = ref(false)
  const batchPriceShow = ref(false)
  const addTypesRef = ref()
  function showFuncHub(type: number) {
    if (!selArrays.value || selArrays.value.length <= 0) {
      common.XmMessage(1, '请至少选择一项')
      return
    }

    let data: unsaleableType[] = []

    if (selArrays.value) {
      data = selArrays.value.map((item: any) => {
        return { itemId: item.id }
      })
    }
    if (type === 1) {
      addTypesDialogShow.value = true
      addTypesRef.value.initForm(selArrays.value)
    } else if (type === 2) {
      batchPriceShow.value = true
    } else if (type === 3) {
      // 上架
      data && setSaleable(data)
    } else if (type === 4) {
      // 下架
      data && setUnsaleable(data)
    } else if (type === 5) {
      // 删除
      data && del(data)
    }
  }
  // table ref
  const paginationTableRef = ref(null)

  async function edit(row: shop, type: number) {
    const item = { itemId: row.id }
    switch (type) {
      case 3:
        {
          const item = { itemId: row.id }
          if (row.status === 0) {
            setSaleable([item])
          } else {
            setUnsaleable([item])
          }
        }
        break
      case 1:
        {
          // 编辑
          // del([item])
          router.push({
            name: 'editShops',
            query: row.id ? { id: row.id } : {},
          })
        }
        break
      case 2:
        {
          // 分享
          // common.XmAlert('待小程序开发')
          const qrObject = {
            config: { showTextbar: false },
            data: [
              {
                name: '分享商品',
                text: [
                  // eslint-disable-next-line max-len
                  `https://devtest.c-sams.com/qrcode?orgId=${store.getters.userInfo.orgId}&userId=${store.getters.userInfo.userId}&scanType=3&shopId=${row.id}`,
                ],
              },
            ],
          }
          // 主节点url+患者id ""
          store.dispatch('qrcode/setQRCodeShowData', qrObject)
        }
        break
      case 4:
        {
          // 删除
          del([item])
        }
        break
      default:
        break
    }
  }

  async function shopUpTopSort(row: shop, index: number) {
    if (index === 0) {
      common.XmAlert('已经到顶')
      return
    }
    await common.syncAlert('是否将该商品置顶')
    common.XmLoading(true)
    await upTopSort({ oid: row.id })
    common.XmLoading(false)
    loadData()
  }
  function shopUpOnceSort(type: number, row: shop, index: number) {
    // @ts-ignore
    if (index + 1 >= d.listData.total && type === 2) {
      common.XmAlert('已经是最底层')
      return
    } else if (index === 0 && type === 1) {
      common.XmAlert('已经到顶')
      return
    }
    const data = { ...d.search, ...form }
    const table = d.listData.data
    useTableSort(
      data,
      row,
      type === 1 ? true : false,
      table,
      upOnceSort,
      getShopList,
      () => {
        // console.log('排序成功')
        // msg
        loadData()
      }
    )
  }
  function paginaChange(pager: any) {
    console.log('sort_order =' + JSON.stringify(pager.sort_order))
    console.log('sort_prop =' + JSON.stringify(pager.sort_prop))
    console.log('sort_column =' + JSON.stringify(pager.sort_column))
    form.sortSales = 0
    form.sortStock = 0
    form.sortPrice = 0
    const { sort_order, sort_prop, sort_column } = pager
    function converOrder(order: string) {
      if (order === 'ascending') {
        return 2
      } else if (order === 'descending') {
        return 1
      } else {
        return 0
      }
    }
    switch (pager.sort_prop) {
      case 'price': {
        form.sortPrice = converOrder(sort_order)
        break
      }
      case 'totalSales': {
        form.sortSales = converOrder(sort_order)
        break
      }
      case 'stock': {
        form.sortStock = converOrder(sort_order)
        break
      }
    }
    d.search.pageIndex = pager.current
    d.search.pageSize = pager.pageSize
    //   loadData()
    loadData()
  }
  // 批量删除
  async function del(data: unsaleableType[]) {
    await common.syncAlert('是否确认删除商品')
    common.XmLoading(true)
    const [err, res] = await to(deleteShops(data))
    common.XmLoading(false)
    if (!err) loadData()
  }

  // 批量下架功能
  async function setUnsaleable(data: unsaleableType[]) {
    await common.syncAlert('是否确认下架商品')
    common.XmLoading(true)
    const [err, res] = await to(unsaleable(data))
    common.XmLoading(false)
    if (!err) loadData()
  }

  // 批量上架功能
  async function setSaleable(data: unsaleableType[]) {
    await common.syncAlert('是否确认上架商品')
    common.XmLoading(true)
    const [err, res] = await to(saleable(data))
    common.XmLoading(false)
    if (!err) loadData()
  }

  // Todo 衍生到最大值 多个表单对比
  function maxPriceChange() {
    const b = minAndMaxHook(form.minPrice, form.maxPrice)
    if (b) {
      // @ts-ignore
      form.maxPrice = null
    }
  }
  function maxStockChange() {
    const b = minAndMaxHook(form.minStock, form.maxStock)
    if (b) {
      // @ts-ignore
      form.maxStock = null
    }
  }
  function minAndMaxHook(min?: any, max?: any) {
    if (min && max) {
      if (parseFloat(min) > parseFloat(max)) {
        common.XmMessage(1, '最小值不能大于最大值')
        return true
      }
    }
    return false
  }
</script>
<style lang="scss" scoped>
  @import '@/styles/mixin.scss';

  .manageShops-container {
    margin: 22px;

    .tools-container {
      margin-bottom: 22px;

      span {
        margin-top: 5px;
        font-size: 12px;
        color: #606266;
      }
    }

    .selClass {
      margin-bottom: 10px;
      padding-left: 10px;
      display: flex;
      align-items: center;

      span {
        margin-left: 2px;
        margin-right: 10px;
      }
    }

    .header-container {
      @include card-shadow;
      padding: 12px;
      background-color: white;

      .el-form-item {
        margin-top: 15px;
        margin-bottom: 15px;
      }
    }

    .content-container {
      @include card-shadow;
      margin-top: 22px;
      background-color: white;
      padding: 11px;

      :deep(.el-radio-group) {
        margin-bottom: 10px !important;
      }

      .add-medicine {
        margin: 12px;
      }

      .cell-img {
        display: flex;

        .imageView-container {
          width: 80px;
          height: 80px;
          border-radius: 5px;
        }

        span {
          text-align: left;
          margin-left: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }
      }

      .shop-table-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
  }
</style>
